<?php

namespace app\admin\service;

use app\admin\validate\GoodsCateValidate;
use support\spark\model\goods\GoodsCate;
use support\spark\model\goods\Goods;
use support\spark\exception\ApiException;

class GoodsCateService
{

    /**
     * 添加商品分类
     * @param $param
     * @return array
     */
    public function addGoodsCate($param)
    {
        if (isset($param['file'])) {
            unset($param['file']);
        }

        // 检验完整性
        $validate = new GoodsCateValidate();
        if (!$validate->check($param)) {
            throw new ApiException($validate->getError(), -1);
        }
        $goodsCateModel = new GoodsCate();
        $has = $goodsCateModel->checkUnique([
            'name' => $param['name']
        ]);
        if (!empty($has)) {
            throw new ApiException('分类名已经存在', -1);
        }

        if ($param['pid'] == 0) {
            $param['level'] = 1;
        } else {
            $parentInfo = $goodsCateModel->getInfoByWhere([
                'id' => $param['pid']
            ], ['pid']);

            if ($parentInfo['pid'] == 0) {
                $param['level'] = 2;
            } else {
                $param['level'] = 3;
            }
        }

        $param['create_time'] = now();
        $param['update_time'] = now();
        $goodsCateModel->insertOne($param);
        return dataReturn(0, '添加成功');
    }


    public function editGoodsCate($param)
    {
        if (isset($param['file'])) {
            unset($param['file']);
        }

        // 检验完整性
        $validate = new GoodsCateValidate();
        if (!$validate->check($param)) {
            throw new ApiException($validate->getError(), -1);
        }

        $goodsCateModel = new GoodsCate();

        $where[] = ['id', '<>', $param['id']];
        $where[] = ['name', '=', $param['name']];
        $has = $goodsCateModel->checkUnique($where);

        if (!empty($has)) {
            throw new ApiException('分类名已经存在', -1);
        }

         $goodsCateModel->updateById($param, $param['id']);
        return dataReturn(0, '修改成功');
    }

    /**
     * 删除商品分类
     * @param $id
     * @return array
     */
    public function delGoodsCate($id)
    {
        // 查询是否有商品使用否则不让删
        $goodsModel = new Goods();
        $goodsInfo = $goodsModel->getInfoByWhere([
            'cate_id' => $id,
            'is_del' => 2
        ],[ 'id']);
        if (!empty($goodsInfo)) {
            throw new ApiException('有商品在使用该分类，不可删除', -1);
        }
        $goodsCateModel = new GoodsCate();
        $has = $goodsCateModel->getInfoByWhere([
            'pid' => $id
        ], ['id']);
        if (!empty($has)) {
            throw new ApiException('该分类下有子分类，不可删除', -1);
        }
        $goodsCateModel = new GoodsCate();
         $goodsCateModel->delById($id);
        return dataReturn(0, '删除成功');
    }

}